package com.lishu.carsafe.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.lishu.carsafe.R;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.UploadFileModel;
import com.lishu.carsafe.utils.ImageUtil;
import com.lishu.carsafe.utils.LogUtil;
import com.lishu.carsafe.utils.NetUtil;
import com.lishu.carsafe.utils.TimeUtil;
import com.lishu.carsafe.utils.ToastUtil;
import java.io.File;

public class TaskDisposeActivity extends BaseActivity implements View.OnClickListener{
    private final int GET_PERMISSION_REQUEST = 200; //权限申请自定义码
    private String taskId;
    private EditText disposeContent;
    private ImageView upload_1, upload_2, video_icon;

    private String mediaType = "0";//0照片1视频
    private String localMediaUrl;
    private String uploadedMediaUrl;
    //private File cameraFile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_dispose);

        taskId = getIntent().getStringExtra("taskId");
        initView();
    }

    private void initView() {
        setTopTitle("任务处理");
        disposeContent = findViewById(R.id.disposeContent);
        upload_1 = findViewById(R.id.upload_1);
        upload_2 = findViewById(R.id.upload_2);
        video_icon = findViewById(R.id.video_icon);
        upload_1.setOnClickListener(this);
        upload_2.setOnClickListener(this);
        findViewById(R.id.submit).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.upload_1:
                if(View.VISIBLE == upload_2.getVisibility()){
                    if("0".equals(mediaType)) {//查看图片
                        Intent intent = new Intent(mContext, PhotoViewActivity.class);
                        intent.putExtra("imagePath", localMediaUrl);
                        startActivity(intent);
                    }else {//播放视频
                        Intent intent = new Intent(mContext, PlayVideoActivity.class);
                        intent.putExtra("videoPath", localMediaUrl);
                        startActivity(intent);
                    }
                }else {
                    getPermissions();
                }
                break;
            case R.id.upload_2:
                getPermissions();
                break;
            case R.id.submit:
                if (TextUtils.isEmpty(disposeContent.getText().toString())) {
                    ToastUtil.showShort("请填写处理内容");
                } else {
                    if (TextUtils.isEmpty(localMediaUrl)) {
                        ToastUtil.showShort("请上传处理照片或视频");
                    } else {
                        sendPicture(localMediaUrl);
                    }
                }
                break;
        }
    }

    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager
                    .PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager
                            .PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager
                            .PERMISSION_GRANTED) {
                startActivityForResult(new Intent(TaskDisposeActivity.this, CameraActivity.class), 100);
            } else {
                //不具有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(TaskDisposeActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);
            }
        } else {
            startActivityForResult(new Intent(TaskDisposeActivity.this, CameraActivity.class), 100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Log.i("carsafe", "picture");
            mediaType = "0";
            localMediaUrl = data.getStringExtra("path");
            ImageUtil.bindImageView(upload_1, localMediaUrl, R.drawable.ic_default_photo);
            video_icon.setVisibility(View.INVISIBLE);
            upload_2.setVisibility(View.VISIBLE);
        }
        if (resultCode == 102) {
            Log.i("carsafe", "video");
            mediaType = "1";
            localMediaUrl = data.getStringExtra("path");
            String firstFramePath = data.getStringExtra("firstFrame");
            ImageUtil.bindImageView(upload_1, firstFramePath, R.drawable.ic_default_photo);
            video_icon.setVisibility(View.VISIBLE);
            upload_2.setVisibility(View.VISIBLE);
        }
        if (resultCode == 103) {
            Toast.makeText(this, "请检查相机权限~", Toast.LENGTH_SHORT).show();
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                if (!writeGranted) {
                    size++;
                }
                //录音权限
                int recordPermissionResult = grantResults[1];
                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!recordPermissionGranted) {
                    size++;
                }
                //相机权限
                int cameraPermissionResult = grantResults[2];
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
                    startActivityForResult(new Intent(TaskDisposeActivity.this, CameraActivity.class), 100);
                } else {
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /*protected void onRequestPermissionsGranted(int requestCode) {
        if (requestCode == 100) {
            checkPermissions(new String[]{Manifest.permission.CAMERA}, 101);
        }else if(requestCode == 101){
            selectPicFromCamera();
        }
    }*/

    /**
     * 通过照相得到照片
     */
   /* public void selectPicFromCamera() {
        if (!(android.os.Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED))) {
            Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/safe");
        if(!dir.exists()){
            dir.mkdir();
        }
        cameraFile = new File(dir, System.currentTimeMillis() + ".jpg");
        LogUtil.d("TaskDisposeActivity cameraFile1 = " + cameraFile);

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(this, "com.lishu.carsafe.fileprovider", cameraFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, apkUri);
        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        }
        startActivityForResult(intent, 99);
    }*/

    /*@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 99){
            if (cameraFile != null && cameraFile.exists()){
                try {
                    //1、得到新拍的照片
                    localImageUrl = cameraFile.getAbsolutePath();
                    LogUtil.d("sendFileLocalPath="+localImageUrl);
                    //2.1、压缩图片
                    //2.2、加入List
                    //3、更新显示
                    ImageUtil.bindImageView(upload_1, localImageUrl, R.drawable.ic_default_photo);
                    upload_2.setVisibility(View.VISIBLE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }*/

    private void sendPicture(String imgPath) {
        showAlways("正在处理，请稍候...");
        HttpLoader.uploadFile("handle", imgPath, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    hide();
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    hide();
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                UploadFileModel uploadFileModel = (UploadFileModel) model;
                if (uploadFileModel != null) {
                    uploadedMediaUrl = uploadFileModel.getData();
                }

                submitTaskDispose(mediaType, uploadedMediaUrl);
            }
        });
    }

    private void submitTaskDispose(String mediaType, String uploadedMediaUrl) {
        String time = TimeUtil.getCurDatetime("yyyy-MM-dd HH:mm:ss");

        HttpLoader.taskHandle(taskId, disposeContent.getText().toString(), time,
            mediaType, uploadedMediaUrl, new HttpBase.IResponseListener() {
                @Override
                public void onResponse(BaseModel model) {
                    hide();
                    if (model == null) {
                        ToastUtil.showShort(R.string.please_check_network);
                        return;
                    }
                    if (!model.success()) {
                        ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                        return;
                    }

                    ToastUtil.showShort("提交成功！");
                    startActivity(new Intent(TaskDisposeActivity.this, TaskActivity.class));
                    finish();
                }
            });
    }
}
